package com.czn.shopdemo.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.czn.shopdemo.model.Result;
import com.czn.shopdemo.service.PaymentService;
import com.czn.shopdemo.utils.AliPayUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author Zenan Chen
 * @date 2023/4/6 14:51
 */
@RestController
@RequestMapping("/payment")
@Api(tags = "支付管理")
public class PaymentController {
    private static final Logger log = LoggerFactory.getLogger(PaymentController.class);
    @Autowired
    private PaymentService paymentService;

    @ApiOperation(value = "支付", notes = "支付")
    @PostMapping(value = "/pay")
    public Object pay(@RequestParam String orderId, HttpServletRequest request) {
        try {
            log.info("------------------------------------->/pay 支付开始");
            paymentService.pay(orderId, request);
            log.info("------------------------------------->/pay 支付结束");
            return Result.ok("支付完成！");
        } catch (Exception e) {
            log.error("------------------------->/pay 支付异常【{}】", e.getMessage());
            return Result.build(201, e.getMessage());
        }
    }

    /**
     * 进行支付宝的支付
     */
    @GetMapping("/alipay")
    @ApiOperation(value = "支付宝支付", notes = "支付宝支付")
    public void aliPay(HttpServletResponse resp) throws AlipayApiException {
        //订单号,测试随机生成->订单的支付金额
        String oid = UUID.randomUUID().toString();
        //测试价格写死,实际开发中根据订单id获取到订单金额
        Double price=20000.00;

        //调用支付宝API
        AlipayClient alipayClient = AliPayUtils.getAlipayClient();
        //构造一个支付请求
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //异步回调,用于接收支付宝服务器的回调请求
        request.setNotifyUrl("http://localhost:8888/shop/payment/result");
        //同步回调,重定向url,跳转到百度...实际开发中根据需求跳转到指定的页面.
        request.setReturnUrl("http://www.baidu.com");

        //封装请求体
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", oid);
        bizContent.put("total_amount", price);
        bizContent.put("subject", "iphone plus 128G");
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");

        request.setBizContent(bizContent.toString());
        AlipayTradePagePayResponse response = null;
        try {
            response = alipayClient.pageExecute(request);
            if(response.isSuccess()){
                System.out.println("调用成功!!OK");
                //拿到支付宝服务器响应的响应体
                String body = response.getBody();
                //将响应体,写入浏览器
                resp.setContentType("text/html;charset=utf-8");
                resp.getWriter().print(body);
                resp.getWriter().close();
            } else {
                System.out.println("支付宝调用失败...");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/result")
    @ApiOperation(value = "支付宝支付回调", notes = "支付宝支付回调")
    public void payResult(){
        System.out.println("接收到支付宝的回调请求!!!");
    }
}
